import Vue from "vue";
import Vuex from "vuex";
import cloneDeep from "lodash/cloneDeep";
import common from "./modules/common";
import user from "./modules/user";

Vue.use(Vuex);

const V_KEY = `V_DDSEF12342E3d`;
import { sStorage, merge, deepClone } from "@/plugins/lib";
// export function vuexToSessionStorage(store) {
//   const savedState = sStorage.getItem(V_KEY);
//   if (savedState) {
//     const newState = merge(store.state, savedState);
//     store.replaceState(newState);
//   }
//   store.subscribe((mutation, state) => {
//     const storeClone = deepClone(state);
//     sStorage.setItem(V_KEY, storeClone);
//   });
// }

export function vuexToSessionStorage(store) {
  const savedState = sStorage.getItem(V_KEY);
  if (savedState) {
    const newState = merge(store.state, savedState);
    try {
      store.commit("user/setToken", newState.user.token);
    } catch (e) {
      // console.log(e)
    }
    store.replaceState(newState);
  }
  store.subscribe((mutation, state) => {
    sStorage.setItem(V_KEY, state);
    // Util.sStorage.setItem('vuex', state);
  });
}

export default new Vuex.Store({
  modules: {
    common,
    user
  },
  mutations: {
    // 重置vuex本地储存状态
    resetStore(state) {
      this.commit("user/setUser", {});
      sStorage.clear();
      // Object.keys(state).forEach(key => {
      //   state[key] = cloneDeep(window["storeState"][key]);
      // });
    }
  },
  plugins: [vuexToSessionStorage]
  // strict: process.env.NODE_ENV !== "production"
});
